//
//  CZPullDownToRefreshControl.swift
//  iOSWeibo10
//
//  Created by 李伟鹏 on 16/5/18.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit


private let CZPullDownToRefreshControlHeight: CGFloat = 60
enum CZPullDownToRefreshStatus{
    case Normal     // 箭头朝下,下拉刷下
    case Pulling    // 箭头朝上,释放刷新
    case Refreshing // 转轮旋转,正在刷新
}
class CZPullDownToRefreshControl: UIView {
    
    func endRefreshing(){
        if currentStatus == CZPullDownToRefreshStatus.Refreshing{
            currentStatus = CZPullDownToRefreshStatus.Normal
            
            UIView.animateWithDuration(CZDefaultDuration, animations: { () -> Void in
                self.superScrollView?.contentInset.top -= CZPullDownToRefreshControlHeight
            })
        }
    }
    
    var pullDownToRefreshCallback: (() -> ())?
    
    func beginRefreshing(){
        currentStatus = CZPullDownToRefreshStatus.Refreshing
    }
    
    private var currentStatus:CZPullDownToRefreshStatus = CZPullDownToRefreshStatus.Normal{
        didSet{
            switch currentStatus{
            case CZPullDownToRefreshStatus.Normal:
                // 风火轮停止旋转
                fhlView.layer.removeAllAnimations()
                // 隐藏风火轮
                fhlView.hidden = true
                // 显示箭头
                arrowView.hidden = false
                messageLabel.text = "下拉刷新"
                UIView.animateWithDuration(CZDefaultDuration, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformIdentity
                })
            case CZPullDownToRefreshStatus.Pulling:
                messageLabel.text = "释放刷新"
                UIView.animateWithDuration(CZDefaultDuration, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case CZPullDownToRefreshStatus.Refreshing:
                self.arrowView.hidden = true
                self.fhlView.hidden = false
                self.messageLabel.text = "正在刷新..."
                let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
                rotationAnimation.toValue = M_PI * 2
                rotationAnimation.duration = CZDefaultDuration
                rotationAnimation.repeatCount = MAXFLOAT
                rotationAnimation.removedOnCompletion =  false
                fhlView.layer.addAnimation(rotationAnimation, forKey: "rotationAnim")
                
                UIView.animateWithDuration(CZDefaultDuration, animations: { () -> Void in
                    self.superScrollView?.contentInset.top += CZPullDownToRefreshControlHeight
                })
                self.pullDownToRefreshCallback?()
            }
        }
    }
    
    private var superScrollView: UIScrollView?
    
     private var NormalToPullingOffset: CGFloat = -124
    
    override init(frame: CGRect) {
        let newFrame = CGRect(x: 0, y: -CZPullDownToRefreshControlHeight, width:  UIScreen.mainScreen().bounds.width, height: CZPullDownToRefreshControlHeight)
        super.init(frame: newFrame)
        preapreUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit{
        superScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    private func preapreUI() {
//        backgroundColor = UIColor.brownColor()
        fhlView.hidden = true
        addSubview(arrowView)
        addSubview(fhlView)
        addSubview(messageLabel)
        
        arrowView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }
        
        fhlView.snp_makeConstraints { (make) -> Void in
            make.centerX.centerY.equalTo(arrowView)
        }
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(arrowView.snp_trailing).offset(10)
            make.centerY.equalTo(self)
        }
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        if let superScrollView = newSuperview as? UIScrollView{
            self.superScrollView = superScrollView
            superScrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        }
    }
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if superScrollView!.dragging{
            if currentStatus == CZPullDownToRefreshStatus.Pulling && superScrollView?.contentOffset.y > NormalToPullingOffset{
                currentStatus = CZPullDownToRefreshStatus.Normal
//                CZPrint(items: "切换到Normal")
            }else if currentStatus == CZPullDownToRefreshStatus.Normal && superScrollView?.contentOffset.y < NormalToPullingOffset{
                currentStatus = CZPullDownToRefreshStatus.Pulling
//                CZPrint(items: "切换到,Pulling")
            }
        }else{
            if currentStatus == CZPullDownToRefreshStatus.Pulling{
                currentStatus = CZPullDownToRefreshStatus.Refreshing
//                CZPrint(items: "切换到,Refreshing")
            }
        }
    }
    
    // MARK: - 懒加载
    /// 箭头
    private lazy var arrowView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    /// 风火轮
    private lazy var fhlView: UIImageView = UIImageView(image: UIImage(named: "tableview_loading"))
    
    /// label
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        
        // 设置
        label.font = UIFont.systemFontOfSize(14)
        label.textColor = UIColor.darkGrayColor()
        label.text = "下拉刷新"
        label.sizeToFit()
        
        return label
    }()
}
